package day52.basic.exception;

import day52.basic.util.AjaxResult;
import day52.basic.commonenum.ErrorCode;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice //贴在类上，这个类就可以在controller的方法执行前，或者执行后做一些事情
public class GlobleExceptionHandler {
    /**
     * 捕获业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public AjaxResult customExceptionHandler(CustomException e){
        e.printStackTrace();
        //通过code获取枚举对象
        ErrorCode error = ErrorCode.getByCode(e.getMessage());
        return AjaxResult
                .me()
                .setCode(error.getCode())
                .setSuccess(false)
                .setMessage(error.getMessage());
    }

    /**
     * 捕获非业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult exception(Exception e){
        e.printStackTrace();
        return AjaxResult
                .me()
                .setCode(ErrorCode.SYSTEM_ERROR.getCode())
                .setSuccess(false)
                .setMessage(ErrorCode.SYSTEM_ERROR.getMessage());
    }

    /**
     * springvalidation对象校验参数异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)//捕获指定的异常
    public AjaxResult methodArgumentExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        return AjaxResult
                .me()
                .setCode("400")
                .setSuccess(false)
                .setMessage("参数异常");
    }

    /**
     * springvalidation单个参数校验异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)//捕获指定的异常
    public AjaxResult constraintViolationExceptionHandler(ConstraintViolationException e){
        e.printStackTrace();
        return AjaxResult
                .me()
                .setCode("400")
                .setSuccess(false)
                .setMessage("参数异常");
    }


}
